import { Context } from 'koa';
import { getManager} from 'typeorm';
import { User } from '../entity/user';
import { JWT_SECRET } from '../constants';
import jwt from 'jsonwebtoken';
import { UnauthorizedException } from '../exceptions';

export default class AuthController {
  public static async login(ctx: Context) {
    const userRepository = getManager().getRepository(User);

    const user = await userRepository
      .createQueryBuilder()
      .where({name: ctx.request.body.name})
      .addSelect('User.password')
      .getOne()

    if(!user){
      ctx.status = 401;
      throw new UnauthorizedException('用户名不存在');
    }else if(user.password === ctx.request.body.password){
      ctx.status = 200;
      ctx.body = { token: jwt.sign({ id: user.id }, JWT_SECRET) };
    }else{
      ctx.status = 401;
      throw new UnauthorizedException('密码错误');
    }
  }

  public static async register(ctx: Context) {
    const userRepository = getManager().getRepository(User);
    const newUser = new User();
    console.log('ctx.request',ctx.request.body)
    newUser.name = ctx.request.body.name;
    newUser.email = ctx.request.body.email;
    newUser.id = new Date().getTime() + '';
    newUser.password = ctx.request.body.password;
    console.log('newUser',newUser)
    // 保存到数据库
    const user = await userRepository.save(newUser);
    console.log('user',user)
    ctx.status = 201;
    ctx.body = user;
  }
}